(function () {
    var $cover_img = $('.cover .cover-img');
    var $u_img = $('.cover .u-img');
    var $t_img = $('.cover .t-img');
    var $text = $('.cover .txt');
    var $next_btn = $('.next-btn');
    var $prev_btn = $('.prev-btn');
    var $file = $('#f');
    var $form = $('form');
    var BW = $('body').width();
    var SH = $(window).height();
    var $date = $('.date');
    var $adTxt = $('#adTxt');
    var $load = $('.loading');


    var emptyFN = function () {
    };
    var sc = SOURCE_CONFIG;
    var idx = 0, max_idx = sc.length - 1;
    var covert_ipt = function (txt) {
        return txt.replace(/［([^］]+)］/g, '<input type="text" name="tt[]" required="required" maxlength="1" value="$1"/>');
    };

//preload image
    /**
     setTimeout(function(){
	for(var i=0; i<sc.length; i++){
		var img = new Image();
		img.src = sc[i][0];
	}
}, 1000);
     **/

    function init(){
        $(document).ready(function(){
            showNotice();
            initScreen();
            var pp = new Pic('#transLateImg');
            pp.picInit();
        });
    }
    init();

    function showNotice() {
        $(document).ready(function () {
            setTimeout(function () {
                $('.notice').remove();
            }, 4000)
        });
    }

    function initScreen()
    {
        $date.css({fontSize:BW/6.4+'px', right:BW/11.034+'px', lineHeight:BW/6.4+'px', top:BW/42.667+'px'});
        $load.find('img').css('margin-top', SH/2 + 'px');
    }


    var show_item = function (idx) {
        var data = sc[idx];
        $cover_img.attr('src', data[0]);
        $text.html(covert_ipt(data[2]));
        $('input[name=index]').val(idx);
    };

    var load_img = function (src, onload) {
        var img = new Image();
        img.onload = function () {
            onload(img);
        };
        img.src = src;
    };

    var sendImg = function (data, succ, err) {
        $load.show();
        var xhr = new XMLHttpRequest();
        succ = succ || emptyFN;
        err = err || emptyFN;
        var onError = function (e) {
            $load.hide();
            err('网络繁忙，请稍候重试(0)');
        };
        var onSuccess = function (rsp) {
            $load.hide();
            if (xhr.status === 200) {
                succ(xhr.responseText);
            } else {
                err('网络繁忙，请稍候重试(1)');
            }
        };
        xhr.open('POST', 'upload.php');
        xhr.onload = onSuccess;
        xhr.onerror = onError;
        xhr.send(data);
    };

    var reset_img = function () {
        load_img($u_img.attr('src'), function (img) {
            //var tf = 'translate3d(0px, 0px, 0px) scale(1, 1)';
            //var css = {
            //    'width': '100%',
            //    'height': img.height * ($cover_img.width() / img.width),
            //    'transform':tf
            //};
            //$u_img.css(css).html(tf);
            //$t_img.css(css).html(tf);


            //pp = null;
            //if (!pp) {
            //    var pp = new Pic('#transLateImg');
            //    pp.picInit();
            //}

        });
    };

    $text.delegate('input', 'click', function () {
        this.select(this);
    });

    $next_btn.click(function () {
        if (idx + 1 > max_idx) {
            idx = 0;
        } else {
            idx = idx + 1;
        }
        show_item(idx);
    });

    $prev_btn.click(function () {
        if (idx == 0) {
            idx = max_idx;
        } else {
            idx = idx - 1;
        }
        show_item(idx);
    });

    //$u_img.load(function () {
    //    if (!$u_img.width()) {
    //        return;
    //    }
    //    $t_img.width($u_img.width())
    //        .height($u_img.height())
    //        .css("left", '20px')
    //        .css("top", '20px');
    //}).trigger('load');

    $file.on('change', function () {
        if (!this.files[0]) {
            return;
        }
        var formData = new FormData();
        var i;
        if (this.files) {
            for (i = 0; i < this.files.length; i++) {
                formData.append($(this).attr('name'), this.files[i]);
            }
        }
        $(this).val('');
        sendImg(formData, function (src) {
            $u_img.attr('src', src);
            reset_img();
            $('input[name=image]').val(src);
        });
    });

    $prev_btn.addClass('transparent');
    $next_btn.addClass('transparent');

    var opts = {domEvents: true};
    var liveScale = 1;
    var currentRotation = 0;

    var width = $u_img.width();
    var height = $u_img.height();
    var left = 0;
    var top = 0;
    var margin;




    $('#submit-btn').click(function () {
        $form.addClass('building');
        $text.find('input').each(function () {
            var t = $(this).val();
            $('<span>' + t + '</span>').insertBefore(this);
            $(this).remove();
        });
        $text.html($text.text());

        html2canvas($('#building-wrap')[0], {
            allowTaint: true,
            taintTest: false,
            onrendered: function (canvas) {
                canvas.id = "mycanvas";
                var dataUrl = canvas.toDataURL();

                $form.removeClass('building');
                var xhr = new XMLHttpRequest();
                xhr.open('POST', 'img.php');
                xhr.onload = function () {
                    if (xhr.status === 200) {
                        location.href = 'share.php?t=' + xhr.responseText;
                    } else {
                        alert('网络繁忙，请稍候重试(1)');
                    }
                };
                xhr.onerror = function () {
                    alert('网络繁忙，请稍候重试(1)');
                };
                var formData = new FormData;
                formData.append('build', dataUrl);
                xhr.send(formData);

            }
        });
        return false;
    });

})();